package cn.edu.dlut.port.isp.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.dlut.port.isp.bean.teach.BerthBean;
import cn.edu.dlut.port.isp.bean.teach.Port;
import cn.edu.dlut.port.isp.bean.teach.ShipBean;
import cn.edu.dlut.port.isp.bean.teach.simulation.PortBean;
import cn.edu.dlut.port.isp.bean.teach.simulation.ResultBean;
import cn.edu.dlut.port.isp.bean.teach.simulation.ResultBean2;
import cn.edu.dlut.port.isp.bean.teach.simulation.ResultBean3;
import cn.edu.dlut.port.isp.bean.teach.simulation.ResultForm;
import cn.edu.dlut.port.isp.bean.teach.simulation.ResultForm2;
import cn.edu.dlut.port.isp.bean.teach.simulation.ResultForm3;
import cn.edu.dlut.port.isp.bean.teach.simulation.SchemeForm;
import cn.edu.dlut.port.isp.bean.teach.simulation.TideBean;
import cn.edu.dlut.port.isp.repostitory.teach.BerthRepository;
import cn.edu.dlut.port.isp.repostitory.teach.ManualSimulationRepository;
import cn.edu.dlut.port.isp.repostitory.teach.PortRepository;
import cn.edu.dlut.port.isp.repostitory.teach.ResultRepository;
import cn.edu.dlut.port.isp.repostitory.teach.ResultRepository2;
import cn.edu.dlut.port.isp.repostitory.teach.ResultRepository3;
import cn.edu.dlut.port.isp.repostitory.teach.ShipRepository;
import cn.edu.dlut.port.isp.repostitory.teach.TideRepository;
import cn.edu.dlut.port.isp.service.TeachService;
@Controller
public class TeachController {
	@Autowired 
private PortRepository portRepository;
	@Autowired 
private BerthRepository berthRepository;
	@Autowired 
private ShipRepository shipRepository;
	@Autowired 
private TideRepository tideRepository;
	@Autowired 
private ManualSimulationRepository manualSimulationRepository;
	@Autowired
private TeachService teachService;
	@Autowired
private ResultRepository resultRepository;
	@Autowired
	private ResultRepository2 resultRepository2;
	@Autowired
	private ResultRepository3 resultRepository3;
	@RequestMapping("/teach1")
	public ModelAndView teach1() {
		ModelAndView mav=new ModelAndView("teach/teach1");
		mav.addObject("list1", portRepository.findAll());	
		return mav;
	}
	
	@RequestMapping("/teach2")
	public ModelAndView teach2() {
		ModelAndView mav=new ModelAndView("teach/teach2");
		return mav;
	}
	@RequestMapping("/teach3")
	public ModelAndView teach3() {
		ModelAndView mav=new ModelAndView("teach/teach3");	
		return mav;
	}
	@RequestMapping("/teach")
	public ModelAndView teach() {
		ModelAndView mav=new ModelAndView("teach");
		return mav;
	}
	@RequestMapping("/login")
	public ModelAndView login() {
		ModelAndView mav=new ModelAndView("login");
		return mav;
	}
	@RequestMapping("/manager")
	public ModelAndView manager() {
		ModelAndView mav=new ModelAndView("manager/managestu");
		return mav;
	}

	
	@RequestMapping("/getResults")
	public ModelAndView getResults() {
		ModelAndView mav=new ModelAndView("teach/results");
		mav.addObject("list", resultRepository.findAll());	
		mav.addObject("ports", portRepository.findAll());	
		return mav;
	}
	
	
	@RequestMapping(path = "/getBerthsByPort.json")
	public @ResponseBody Map<String,Object> getBerthsByPort(@RequestParam int port_id) {
		Map<String,Object> map=new HashMap<String,Object>();	    
		map.put("list11", berthRepository.findByPortid(port_id));
		return map;
	}
	
	
	@RequestMapping(path = "/getShipsByPort.json")
	public @ResponseBody Map<String,Object> getShipsByPort(@RequestParam int port_id) {
		Map<String,Object> map=new HashMap<String,Object>();
		List<BerthBean> berths=berthRepository.findByPortid(port_id);
		List<ShipBean> ships=new ArrayList<ShipBean>();
		for(BerthBean berth:berths)
		{
			List<ShipBean> res=shipRepository.findByCargoTypeIDAndTonnageDWTStartingWith(berth.getCargoTypeID(), berth.getTonnage()+"");
				for(int i=0;i<res.size();i++)
				{
					
					if(res.get(i).getTonnageDWT().contains(berth.getTonnage()+"0")) {
						res.remove(i);
						break;
					}
					res.get(i).setTonnageDWT(berth.getTonnage()+"");
				}
			ships.addAll(res);

		}
		map.put("list12",ships);
		return map;
	}
	
	@RequestMapping(path = "/getTidesByCargotype.json")
	public @ResponseBody Map<String,Object> getTidesByCargotype(@RequestParam int cargoTypeId) {
		Map<String,Object> map=new HashMap<String,Object>();	    
		map.put("list3", tideRepository.findByCargoTypeId(cargoTypeId));
		return map;
	}
	
	@RequestMapping(path = "/getSimulationDataByPort.json")
	public @ResponseBody Map<String,Object> getSimulationDataByPort(@RequestParam int port_id) {
		Map<String,Object> map=new HashMap<String,Object>();	    
		map.put("list4", manualSimulationRepository.findAllByPortId(port_id));
		return map;
	}
	
	
	@RequestMapping(path = "/doSimulation.json")
	public @ResponseBody Map<String,Object> doSimulation(@RequestBody SchemeForm sdata) {
		System.out.println(sdata);
		 List<BerthBean> listb1=berthRepository.findByPortid(sdata.getPort_id());
         ArrayList<cn.edu.dlut.port.isp.bean.teach.simulation.BerthBean> listb2=new ArrayList<cn.edu.dlut.port.isp.bean.teach.simulation.BerthBean>();
     	for(BerthBean b:listb1)
     	{
     		listb2.add(b.changeToSim(b));
     	}
     	 List<Port> listp=portRepository.findAll();
     	TideBean tb=null;
     	PortBean pb=new PortBean();
     	 for(Port p:listp)
     	 {
     		 if(p.getId()==sdata.getPort_id())
     		 {
     			 //int tideType, double tideRange, double averageWL, double desHWL, double desLWL, double extHWL, double extLWL
     			 tb=new TideBean(p.getTideTypeID(),p.getTideRange(),p.getAverageWL(),p.getDesHWL(),p.getDesLWL(),p.getExtHWL(),p.getExtLWL());    			   			
     			 pb.setBerths(listb2);
     			 pb.setCrossCurrentV(p.getCrossCurrentV());
     			 pb.setDepoistState(p.getDespoit());  
     			 pb.setLongitudinalCurrentV(p.getLongitudinalCurrentV());
     			 pb.setOperationalDay(p.getOperationalDay());
     			 pb.setTideBean(tb);   			
     			 pb.setWaveAngle(p.getWaveAngle());
     			 pb.setWaveHeight(p.getWaveHeight());
     			 pb.setWavePeriod(p.getWavePeriod());
     			// System.out.println(pb);
     		 }
     	 }
     	
        teachService.initPort(pb);
		Map<String,Object> map=new HashMap<String,Object>();
		Object res= teachService.checkAndRunModelParams(sdata);
		if(res instanceof String)
		{
			String error="";
			if("e1".equals(res))
				error="请输入模型参数！";
			else if("e2".equals(res))
				error="请输入数字！";
			else
				error="方案" + res + "航道通航水位不能满足船舶通航要求！";
			map.put("msg", error);
			map.put("list62", null);
		}else
		{
			map.put("msg","仿真成功");
			map.put("list62",res);
		}
		return map;
	}
	
	
	@RequestMapping(path = "/saveResult.json")
	public @ResponseBody Map<String,Object> saveResult(@RequestBody ResultForm rdata) throws ParseException {
		//System.out.println(rdata);
		Map<String,Object> map=new HashMap<String,Object>();
		if(rdata==null||rdata.getList()==null)
		{
			map.put("msg","仿真结果数据格式有误，请检查。");
			map.put("res","0");
			return map;
		}
		
		String sno=rdata.getSno();
		String sname=rdata.getSname();
		List<ResultBean> users=resultRepository.findBySnoAndSname(sno, sname);

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String s = sdf.format(new Date());
			Date date =  sdf.parse(s);
			int result=0;
			int flag=0;//0表示新增；1表示修改
		if(users!=null&&users.size()>0)//已存在该学生的仿真结果记录
		{
			flag=1;
			resultRepository.deleteAllBySnoAndSname(sno,sname);//删除掉以前的结果
		}
		//新增仿真结果
		for(int i=0;i<rdata.getList().size();i++) {
			String waittime=rdata.getList().get(i).getWaittime();
			String waitcost=rdata.getList().get(i).getWaitcost();
			String soilquantity=rdata.getList().get(i).getSoilquantity();
			String soilcost=rdata.getList().get(i).getSoilcost();
			ResultBean newRb=new ResultBean();
			newRb.setSname(sname);
			newRb.setSno(sno);
			newRb.setWaittime(waittime);
			newRb.setWaitcost(waitcost);
			newRb.setSoilquantity(soilquantity);
			newRb.setSoilcost(soilcost);
			newRb.setCreatetime(date);
			newRb.setIssdec(rdata.getList().get(i).getIssdec());
			newRb.setMulti(rdata.getList().get(i).getMulti());
			newRb.setWangle(rdata.getList().get(i).getWangle());
			newRb.setWidc(rdata.getList().get(i).getWidc());
			newRb.setBangle(rdata.getList().get(i).getBangle());
			newRb.setHeiz0(rdata.getList().get(i).getHeiz0());
			newRb.setSoil(rdata.getList().get(i).getSoil());
			newRb.setBangle(rdata.getList().get(i).getBangle());
			newRb.setDepz2(rdata.getList().get(i).getDepz2());
			newRb.setDepz3(rdata.getList().get(i).getDepz3());
			newRb.setDepz4(rdata.getList().get(i).getDepz4());
			newRb.setWidw(rdata.getList().get(i).getWidw());
			newRb.setDep0(rdata.getList().get(i).getDep0());
			newRb.setDep(rdata.getList().get(i).getDep());
			newRb.setV(rdata.getList().get(i).getV());
			newRb.setTs(rdata.getList().get(i).getTs());
			newRb.setWidth(rdata.getList().get(i).getWidth());
			newRb.setHeight(rdata.getList().get(i).getHeight());
			newRb.setAssrate(rdata.getList().get(i).getAssrate());
			newRb.setLength(rdata.getList().get(i).getLength());
			newRb.setWaterlevel(rdata.getList().get(i).getWaterlevel());
			newRb.setPortid(rdata.getList().get(i).getPortid());
			
			ResultBean rb=resultRepository.save(newRb);
			result++;
			
			if(rdata.getList().size()==result&&flag==0)
				map.put("msg","已经保存了学号"+sno+"同学的仿真结果。");
			else if(rdata.getList().size()==result&&flag==1)
				map.put("msg","已经更新了学号"+sno+"同学的仿真结果。");
			else if(rdata.getList().size()!=result&&flag==0)
				map.put("msg","增加结果失败。");
			else
				map.put("msg","更新结果失败。");
		}
		map.put("res", 1);
		return map;
	}
	
	
	@RequestMapping(path = "/saveResult2.json")
	public @ResponseBody Map<String,Object> saveResult2(@RequestBody ResultForm2 rdata) throws ParseException {
		//System.out.println(rdata);
		Map<String,Object> map=new HashMap<String,Object>();
		if(rdata==null||rdata.getList()==null)
		{
			map.put("msg","仿真结果数据格式有误，请检查。");
			map.put("res","0");
			return map;
		}
		
		String sno=rdata.getSno();
		String sname=rdata.getSname();
		List<ResultBean2> users=resultRepository2.findBySnoAndSname(sno, sname);

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String s = sdf.format(new Date());
			Date date =  sdf.parse(s);
			int result=0;
			int flag=0;//0表示新增；1表示修改
		if(users!=null&&users.size()>0)//已存在该学生的仿真结果记录
		{
			flag=1;
			resultRepository2.deleteAllBySnoAndSname(sno,sname);//删除掉以前的结果
		}
		//新增仿真结果
		for(int i=0;i<rdata.getList().size();i++) {
			
			ResultBean2 newRb=new ResultBean2();
			newRb.setSname(sname);
			newRb.setSno(sno);
			newRb.setCreatetime(date);
			newRb.setBst(rdata.getList().get(i).getBst());
			newRb.setNumit(rdata.getList().get(i).getNumit());
			newRb.setNumqc(rdata.getList().get(i).getNumqc());
			newRb.setQqc1(rdata.getList().get(i).getQqc1());
			newRb.setQqc2(rdata.getList().get(i).getQqc2());
			resultRepository2.save(newRb);
			result++;
			
			if(rdata.getList().size()==result&&flag==0)
				map.put("msg","已经保存了学号"+sno+"同学的仿真结果。");
			else if(rdata.getList().size()==result&&flag==1)
				map.put("msg","已经更新了学号"+sno+"同学的仿真结果。");
			else if(rdata.getList().size()!=result&&flag==0)
				map.put("msg","增加结果失败。");
			else
				map.put("msg","更新结果失败。");
		}
		map.put("res", 1);
		System.out.println(map);
		return map;
	}
	
	@RequestMapping(path = "/saveResult3.json")
	public @ResponseBody Map<String,Object> saveResult3(@RequestBody ResultForm3 rdata) throws ParseException {
		//System.out.println(rdata);
		Map<String,Object> map=new HashMap<String,Object>();
		if(rdata==null||rdata.getList()==null)
		{
			map.put("msg","仿真结果数据格式有误，请检查。");
			map.put("res","0");
			return map;
		}
		
		String sno=rdata.getSno();
		String sname=rdata.getSname();
		List<ResultBean3> users=resultRepository3.findBySnoAndSname(sno, sname);

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String s = sdf.format(new Date());
			Date date =  sdf.parse(s);
			int result=0;
			int flag=0;//0表示新增；1表示修改
		if(users!=null&&users.size()>0)//已存在该学生的仿真结果记录
		{
			flag=1;
			resultRepository3.deleteAllBySnoAndSname(sno,sname);//删除掉以前的结果
		}
		//新增仿真结果
		for(int i=0;i<rdata.getList().size();i++) {
			
			ResultBean3 newRb=new ResultBean3();
			newRb.setSname(sname);
			newRb.setSno(sno);
			newRb.setExpno(rdata.getList().get(i).getExpno());
			newRb.setCreatetime(date);
			newRb.setDensbsmax(rdata.getList().get(i).getDensbsmax());
			newRb.setDensbsmin(rdata.getList().get(i).getDensbsmin());
			newRb.setDensbsave(rdata.getList().get(i).getDensbsave());
			newRb.setDenslcpave(rdata.getList().get(i).getDenslcpave());
			newRb.setDenslcpmin(rdata.getList().get(i).getDenslcpmin());
			newRb.setDenslcpmax(rdata.getList().get(i).getDenslcpmax());
			newRb.setDensrcpave(rdata.getList().get(i).getDensrcpave());
			newRb.setDensrcpmin(rdata.getList().get(i).getDensrcpmin());
			newRb.setDensrcpmax(rdata.getList().get(i).getDensrcpmax());
			newRb.setDsbusave(rdata.getList().get(i).getDsbusave());
			newRb.setDsbusmax(rdata.getList().get(i).getDsbusmax());
			newRb.setDsbusmin(rdata.getList().get(i).getDsbusmin());
			newRb.setDscarave(rdata.getList().get(i).getDscarave());
			newRb.setDscarmax(rdata.getList().get(i).getDscarmax());
			newRb.setDscarmin(rdata.getList().get(i).getDscarmin());
			newRb.setWtbpave(rdata.getList().get(i).getWtbpave());
			newRb.setWtbpmin(rdata.getList().get(i).getWtbpmin());
			newRb.setWtbpmax(rdata.getList().get(i).getWtbpmax());
			newRb.setWtpcpave(rdata.getList().get(i).getWtpcpave());
			newRb.setWtpcpmin(rdata.getList().get(i).getWtpcpmin());
			newRb.setWtpcpmax(rdata.getList().get(i).getWtpcpmax());
			newRb.setWtvehave(rdata.getList().get(i).getWtvehave());
			newRb.setWtvehmax(rdata.getList().get(i).getWtvehmax());
			newRb.setWtvehmin(rdata.getList().get(i).getWtvehmin());
			ResultBean3 rb=resultRepository3.save(newRb);
			result++;
			
			if(rdata.getList().size()==result&&flag==0)
				map.put("msg","已经保存了学号"+sno+"同学的仿真结果。");
			else if(rdata.getList().size()==result&&flag==1)
				map.put("msg","已经更新了学号"+sno+"同学的仿真结果。");
			else if(rdata.getList().size()!=result&&flag==0)
				map.put("msg","增加结果失败。");
			else
				map.put("msg","更新结果失败。");
		}
		map.put("res", 1);
		System.out.println(map);
		return map;
	}
}
